package com.mofofa.maozy.repay.naira

import android.annotation.SuppressLint
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import co.paystack.android.Paystack
import co.paystack.android.PaystackSdk
import co.paystack.android.Transaction
import co.paystack.android.model.Card
import co.paystack.android.model.Charge
import com.mofofa.maozy.R
import com.mofofa.maozy.base.BaseActivity
import com.mofofa.maozy.components.dialog.MessageDialog
import com.mofofa.maozy.components.dialog.DatePickerDialog
import com.mofofa.maozy.data.ReqBase
import com.mofofa.maozy.data.ReqPaystackOrderInitNgn
import com.mofofa.maozy.data.RevObjPaystackOrderInitNgn
import com.mofofa.maozy.databinding.ActivityMaozyRepayPaystackBinding
import com.mofofa.maozy.enums.PageTagEnum
import com.mofofa.maozy.extend.getMaozySafeMaozyTag
import com.mofofa.maozy.extend.recordMaozyClickMaozyEvent
import com.mofofa.maozy.extend.startMaozyToMaozyNextMaozyActivityMaozyForMaozySingleMaozyTop
import com.mofofa.maozy.home.HomeActivity
import com.mofofa.maozy.launch.UserStateViewModel
import com.mofofa.maozy.repay.RepayViewModel

@SuppressLint("CustomSplashScreen")
class PaystackRepayNgnActivity : BaseActivity() {

    private lateinit var mMaozyActivityMaozyBinding: ActivityMaozyRepayPaystackBinding
    private lateinit var mDatePickerDialog: DatePickerDialog

    private val mUserStateViewModel by lazy {
        ViewModelProvider(this).get(UserStateViewModel::class.java)
    }

    private val mRepayViewModel by lazy {
        ViewModelProvider(this).get(RepayViewModel::class.java)
    }

    private val mPaystackNgnViewModel by lazy {
        ViewModelProvider(this).get(PaystackNgnViewModel::class.java)
    }

    override fun onMaozyBindingMaozyViewMaozyModel(): List<ViewModel>? {
        val list = mutableListOf<ViewModel>()
        list.add(mRepayViewModel)
        list.add(mUserStateViewModel)
        list.add(mPaystackNgnViewModel)
        return list
    }

    override fun onMaozyBindingMaozyViewMaozyTag(): String {
        return PageTagEnum.repay_paystack_naira.name.uppercase()
    }

    override fun onMaozyBindingMaozyContentMaozyView(): View {
        mMaozyActivityMaozyBinding = ActivityMaozyRepayPaystackBinding.inflate(layoutInflater)
        return mMaozyActivityMaozyBinding.root
    }

    override fun onMaozyContentMaozyViewMaozyBinded() {
        try {
            //初始化paystack
            PaystackSdk.initialize(this)
            //初始化日期框
            mDatePickerDialog = DatePickerDialog()
            mDatePickerDialog.mMaozyDateMaozyMode = R.integer.ActionModeDatePickerYYMM
            mDatePickerDialog.mMaozyOnMaozyActionMaozyListener = { _, date ->
                mMaozyActivityMaozyBinding.formInputRepayPaystackCardExpires.setMaozyContent(date)
            }
            //获取paystack sdk初始化信息回调
            mPaystackNgnViewModel.onMaozyInitMaozyPaystackMaozySdkMaozyLiveData.observe(this) {
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        //调起支付
                        startMaozyPaystackMaozyRepay(result)
                    }
                }
            }
            //获取用户状态回调
            mRepayViewModel.onMaozyFetchMaozyIsMaozyRepayMaozyNowMaozyLiveData.observe(this) {
                if (it.isSuccess) {
                    if (it.getOrNull() != true) {
                        startMaozyToMaozyNextMaozyActivityMaozyForMaozySingleMaozyTop<HomeActivity>()
                    }
                }
            }
            //点击日期
            mMaozyActivityMaozyBinding.formInputRepayPaystackCardExpires.setMaozyOnMaozyActionMaozyClickMaozyListener {
                mDatePickerDialog.showNow(
                    supportFragmentManager,
                    DatePickerDialog::class.java.simpleName
                )
            }
            mMaozyActivityMaozyBinding.submitRepayPaystack.setOnClickListener {
                val formDataCompleteState =
                    isMaozyAllMaozyFormMaozyDataMaozyCompleted()
                mMaozyActivityMaozyBinding.submitRepayPaystack.recordMaozyClickMaozyEvent(formDataCompleteState)
                if (formDataCompleteState.isBlank()) {
                    val cvv = mMaozyActivityMaozyBinding.formInputRepayPaystackCvv.getMaozyContent()
                    val cardNum =
                        mMaozyActivityMaozyBinding.formInputRepayPaystackBankAccount.getMaozyContent()
                    val dateList =
                        mMaozyActivityMaozyBinding.formInputRepayPaystackCardExpires.getMaozyContent()
                            .split("-")
                    val year = dateList[0]
                    val month = dateList[1]

                    mPaystackNgnViewModel.mMaozyCardMaozyNum = cardNum
                    mPaystackNgnViewModel.mMaozyEMaozyYear = year
                    mPaystackNgnViewModel.mMaozyEMaozyMonth = month
                    mPaystackNgnViewModel.mMaozyEMaozyCvv = cvv

                    mPaystackNgnViewModel.initMaozyPaystackMaozySdk(
                        ReqPaystackOrderInitNgn(
                            cardNumber = cardNum,
                            expiryYear = year,
                            expiryMonth = month,
                            cvv = cvv,
                        )
                    )
                } else {
                    Toast.makeText(
                        this,
                        "Please complete all required fields",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun isMaozyAllMaozyFormMaozyDataMaozyCompleted(): String {
        val notFillOptions = mutableListOf<String>()
        if (!mMaozyActivityMaozyBinding.formInputRepayPaystackBankAccount.isMaozyFormMaozyCompleted()) {
            val gTag = mMaozyActivityMaozyBinding.formInputRepayPaystackBankAccount.getMaozySafeMaozyTag()
            if (gTag.isNotBlank()) {
                notFillOptions.add(gTag)
            }
        }
        if (!mMaozyActivityMaozyBinding.formInputRepayPaystackCvv.isMaozyFormMaozyCompleted()) {
            val gTag = mMaozyActivityMaozyBinding.formInputRepayPaystackCvv.getMaozySafeMaozyTag()
            if (gTag.isNotBlank()) {
                notFillOptions.add(gTag)
            }
        }
        if (!mMaozyActivityMaozyBinding.formInputRepayPaystackCardExpires.isMaozyFormMaozyCompleted()) {
            val gTag = mMaozyActivityMaozyBinding.formInputRepayPaystackCardExpires.getMaozySafeMaozyTag()
            if (gTag.isNotBlank()) {
                notFillOptions.add(gTag)
            }
        }
        if (notFillOptions.isEmpty()) {
            return ""
        }
        notFillOptions.add(0, "NOT_FILL")
        return notFillOptions.joinToString("#")
    }

    /** 启动paystack sdk 还款 */
    private fun startMaozyPaystackMaozyRepay(revObjInitPaystackInit: RevObjPaystackOrderInitNgn) {
        if (revObjInitPaystackInit.accessCode.isNotBlank() and revObjInitPaystackInit.pubKey.isNotBlank()) {
            PaystackSdk.setPublicKey(revObjInitPaystackInit.pubKey)

            val cardNumber = mPaystackNgnViewModel.mMaozyCardMaozyNum
            val cvv = mPaystackNgnViewModel.mMaozyEMaozyCvv
            val year = mPaystackNgnViewModel.mMaozyEMaozyYear.toInt()
            val month = mPaystackNgnViewModel.mMaozyEMaozyMonth.toInt()

            val card = Card(cardNumber, month, year, cvv)
            val charge = Charge()
            charge.card = card
            charge.accessCode = revObjInitPaystackInit.accessCode

            PaystackSdk.chargeCard(
                this,
                charge,
                object : Paystack.TransactionCallback {
                    override fun onSuccess(transaction: Transaction?) {
                        println("PaystackSdk: onSuccess")
                        mRepayViewModel.fetchMaozyIsMaozyRepayMaozyNow(
                            ReqBase()
                        )
                    }

                    override fun beforeValidate(transaction: Transaction?) {
                        println("PaystackSdk: beforeValidate")
                    }

                    override fun onError(error: Throwable?, transaction: Transaction?) {
                        println("PaystackSdk: onError")
                        showMaozyPaystackMaozyRepayMaozyError()
                    }
                })
        } else {
            showMaozyPaystackMaozyRepayMaozyError()
        }
    }

    private fun showMaozyPaystackMaozyRepayMaozyError() {
        MessageDialog.showMaozyDialog(
            supportFragmentManager,
            "Repay operation failed, please try again later."
        )
    }
}